// const jsonwebtoken=require('jsonwebtoken')
const jwt=require('koa-jwt')
const Router=require('koa-router')
const router=new Router({prefix:'/users'}) //添加前缀，后续写可省略前缀
const {find,findById,create,update,delete:del,login,checkOwner, listFollowing, follow, unfollow, listFollowers,checkUserExist,followTopic,unfollowTopic, listFollowingTopics} =require('../controllers/users')
const {checkTopicExist}=require('../controllers/topics')
const {secret} =require('../config')

// const auth=async(ctx,next)=>{
//     const {authorization=''}=ctx.request.header
//     const token=authorization.replace('Bearer ','')
//     try {
//         const user=jsonwebtoken.verify(token,secret)
//         ctx.state.user=user
//     } catch (err) {
//         ctx.throw(401,err.message)
//     }
//     await next()
// }
const auth=jwt({secret})


router.get('/',find)
router.post('/',create)
router.get('/:id',findById)
router.patch('/:id',auth,checkOwner,update)  //put整体替换，patch可局部更新
router.delete('/:id',auth,checkOwner,del)
router.post('/login',login)
router.get('/:id/following',listFollowing)
router.get('/:id/followers',listFollowers)
router.put('/follow/:id',auth,checkUserExist,follow)
router.delete('/unfollow/:id',auth,checkUserExist,unfollow)
router.get('/:id/followingTopics',listFollowingTopics)
router.put('/followTopics/:id',auth,checkTopicExist,followTopic)
router.delete('/unfollowTopics/:id',auth,checkTopicExist,unfollowTopic)


module.exports=router